package com.shenrongrong.interceptor;
//获取请求头的token信息
import com.alibaba.druid.util.StringUtils;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.shenrongrong.exception.CustomerException;
import com.shenrongrong.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    // JwtInterceptor.java 的 preHandle 方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 放行白名单
        String requestUri = request.getRequestURI();
        if ("/loginUser".equals(requestUri)) {
            return true;
        }
        // 2. 获取Token
        String token = request.getHeader("token");
//        if (token != null && token.startsWith("Bearer ")) {
//            token = token.substring(7); // 去除 Bearer 前缀
//        }
        // 3. 校验Token（精准异常捕获）
        try {
            JwtUtil.verifyAndDecode(token); // 验证Token有效性
            return true;
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
            throw new CustomerException("401", "Token缺失，请先登录");//抛出了异常 异常由GlobalExceptionHandler.java捕获然后传递给前段
        } catch (TokenExpiredException e) {
            System.out.println(e.getMessage());
            throw new CustomerException("401", "登录已过期，请重新登录");
        } catch (SignatureVerificationException e) {
            System.out.println(e.getMessage());
            throw new CustomerException("401", "Token签名错误，可能已被篡改");
        } catch (InvalidClaimException e) {
            System.out.println(e.getMessage());
            throw new CustomerException("401", "Token无效，发行人不匹配");
        } catch (JWTDecodeException e) {
            System.out.println(e.getMessage());
            throw new CustomerException("401", "Token格式错误");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new CustomerException("401", "Token验证失败：" + e.getMessage());
        }
    }


}
